package com.wey.springboot.task;

import com.wey.springboot.bean.QuartzTask;
import com.wey.springboot.mapper.QuartzTaskMapper;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Component
public class MessageRemindTask implements Job {
  @Autowired
  QuartzTaskMapper mapper;
  @Autowired
  StringRedisTemplate stringRedisTemplate;
  private static final SimpleDateFormat sdf;

  static {
    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  }

  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    // 通过任务标记获得任务id
    JobKey key = jobExecutionContext.getJobDetail().getKey();
    String[] split = key.toString().split("\\.");
    Integer taskId = Integer.parseInt(split[split.length - 1]);
    // 查询任务详情
    QuartzTask quartzTask = mapper.selectById(taskId);
    String name = quartzTask.getName();
    // 存入redis
    ListOperations<String, String> stringStringListOperations = stringRedisTemplate.opsForList();
    stringStringListOperations.rightPush("task-"+name,sdf.format(new Date()));
    System.out.println("定时任务-短信提醒-" + name + "：" + sdf.format(new Date()));
  }
}
